﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;

namespace jsweb.ContentTypes
{
   class HtmlContent : ContentProvider
   {
      public MVC MvcInstance { get; set; }

      public HtmlContent(MVC mvcInstance)
      {
         MvcInstance = mvcInstance;
      }

      
      /// <summary>
      /// Handles the request as an html-request
      /// </summary>
      /// <param name="context"></param>
      /// <returns></returns>
      public override bool HandleContent(HttpListenerContext context)
      {
         // Set default content-type
         context.Response.ContentType = "text/html";
         context.Response.ContentEncoding = Encoding.UTF8;
         var outstream = new StreamWriter(context.Response.OutputStream, context.Response.ContentEncoding);

         // Handle html-request
         //if (context.Request.Url.Segments.Length < 3)
         //{
         //   // Set error code
         //   context.Response.StatusCode = (int) HttpStatusCode.NotFound;
         //   return false;
         //}

         var mapping = context.Request.Url.LocalPath;
         string function = "";

         // Act on get or post requests
         if (context.Request.HttpMethod == "GET")
         {
            // Check for mapping
            if (!MvcInstance.GetActions.ContainsKey(context.Request.Url.LocalPath))
            {
               // Set error code
               context.Response.StatusCode = (int) HttpStatusCode.NotFound;
               return false;
            }
            function = MvcInstance.GetActions[context.Request.Url.LocalPath];
         }
         else if (context.Request.HttpMethod == "POST")
         {
            // Check for mapping
            if (!MvcInstance.PostActions.ContainsKey(context.Request.Url.LocalPath))
            {
               // Set error code
               context.Response.StatusCode = (int)HttpStatusCode.NotFound;
               return false;
            }
            function = MvcInstance.PostActions[context.Request.Url.LocalPath];
         }

         // Map query
         string queryObj = null;
         if (context.Request.QueryString.Count > 0)
         {
            queryObj = "{";
            foreach (string key in context.Request.QueryString)
            {
               var value = context.Request.QueryString[key];
               queryObj += key + ":" + "'" + value + "',";
            }
            queryObj = queryObj.Remove(queryObj.Length - 1);
            queryObj += "}";
         }
         
         // Execute action
         var executive = new MVCExecutive(context, mapping, function, queryObj, context.Request.HttpMethod == "POST");
         outstream.Write(executive.Execute().ToString());
         outstream.Flush();

         return true;
      }
   }
}
